<template>
  <div class="order-list-container">
    <!-- 搜索功能区域 -->
    <el-form inline class="search-form">
      <el-form-item label="区域">
        <el-input v-model="searchParams.area" placeholder="请输入区域" clearable @clear="fetchOrderData"></el-input>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input v-model="searchParams.address" placeholder="请输入详细地址" clearable @clear="fetchOrderData"></el-input>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="searchParams.status" placeholder="请选择订单状态" clearable @change="fetchOrderData">
          <el-option label="未发放" :value="0"></el-option>
          <el-option label="已发放" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchOrderData">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单列表表格 -->
    <el-table :data="filteredOrderList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="number" label="订单编号" width="200" align="center"></el-table-column>
      <el-table-column prop="goodsName" label="商品名称" width="200" align="center"></el-table-column>
      <el-table-column prop="area" label="区域" width="200" align="center"></el-table-column>
      <el-table-column prop="address" label="详细地址" width="250" align="center"></el-table-column>
      <el-table-column prop="status" label="订单状态" width="120" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" class="delete-btn" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="total"></el-pagination>

    <!-- 编辑订单状态的对话框 -->
    <el-dialog title="编辑订单状态" :visible.sync="editDialogVisible" width="400px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="订单状态">
          <el-select v-model="editForm.status" placeholder="请选择订单状态">
            <el-option label="未发放" :value="0"></el-option>
            <el-option label="已发放" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
export default {
  data() {
    return {
      searchParams: {
        area: "",
        address: "",
        status: null,
        page: 1,
        pageSize: 10,
      },
      orderList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      editDialogVisible: false,
      editForm: {
        id: null,
        status: null,
      },
    };
  },
  computed: {
    // 过滤掉 delFlag 为 1 的数据
    filteredOrderList() {
      return this.orderList.filter((item) => item.delFlag === 0);
    },
  },
  created() {
    this.fetchOrderData();
  },
  methods: {
    // 获取订单数据
    fetchOrderData() {
      this.loading = true;
      this.searchParams.page = this.currentPage;
      this.searchParams.pageSize = this.pageSize;

      request
        .get("/admin/order/pageSearch", { params: this.searchParams })
        .then((response) => {
          if (response && response.code === 1) {
            this.orderList = response.data.records || [];
            this.total = response.data.total || 0;
            // 获取每个订单对应的商品名称
            this.fetchGoodsNames();
          } else {
            this.$message.error("获取订单数据失败：" + response.message);
          }
        })
        .catch((error) => {
          console.error("获取订单数据失败：", error);
          this.$message.error("获取订单数据失败：" + error.message);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取每个订单对应的商品名称
    fetchGoodsNames() {
      // 使用 Promise.all 确保所有商品名称获取完成后才更新表格
      const requests = this.orderList.map((order) => {
        if (order.goodsId) {
          return request.get(`/admin/goods/find/${order.goodsId}`);
        }
        return Promise.resolve();
      });

      Promise.all(requests).then((responses) => {
        responses.forEach((response, index) => {
          if (response && response.code === 1) {
            this.$set(this.orderList[index], 'goodsName', response.data.name);
          }
        });
      }).catch((error) => {
        console.error("获取商品名称失败：", error);
      });
    },
    // 每页显示记录数改变时的处理
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchOrderData(); // 重新获取数据
    },
    // 当前页码改变时的处理
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchOrderData(); // 重新获取数据
    },
    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        0: "未发放",
        1: "已发放",
      };
      return statusMap[status] || "未知状态";
    },
    // 获取订单状态标签类型
    getStatusTagType(status) {
      const statusTypeMap = {
        0: "info",
        1: "success",
      };
      return statusTypeMap[status] || "info";
    },
    // 编辑订单状态
    handleEdit(row) {
      this.editForm = {
        id: row.id,
        status: row.status,
      };
      this.editDialogVisible = true;
    },
    // 提交编辑
    submitEdit() {
      request
        .put("/admin/order/update", {
          id: this.editForm.id,
          status: this.editForm.status,
        })
        .then((response) => {
          if (response && response.code === 1) {
            this.$message.success("订单状态更新成功");
            this.editDialogVisible = false;
            this.fetchOrderData(); // 刷新列表
          } else {
            this.$message.error("订单状态更新失败：" + response.message);
          }
        })
        .catch((error) => {
          console.error("订单状态更新失败：", error);
          this.$message.error("订单状态更新失败：" + error.message);
        });
    },
    // 删除订单
    handleDelete(row) {
      this.$confirm("此操作将永久删除该订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          request
            .delete("/admin/order/delete", { params: { id: row.id } })
            .then((response) => {
              if (response && response.code === 1) {
                this.
                  message.success("订单删除成功");
                this.fetchOrderData(); // 刷新列表
              } else {
                this.
                  message.error("订单删除失败：" + response.message);
              }
            })
            .catch((error) => {
              console.error("订单删除失败：", error);
              this.
                message.error("订单删除失败：" + error.message);
            });
        })
        .catch(() => {
          this.
            message.info("已取消删除");
        });
    },
  },
};
</script>
<style scoped>
.order-list-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.delete-btn {
  color: #f56c6c;
}
</style>